package com.yxjx.duoxue.customview;

import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer.RoundedDrawable;
import com.yxjx.duoxue.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region.Op;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;


public class YxImageView extends ImageView {
	
	private static final int TYPE_FIX_WIDTH = 0;
	private static final int TYPE_FIX_HEIGHT = 1;
	private static final int TYPE_FIX_HEIGHT_MATCH_WIDTH = 2; // fix height  and width match_parent.
	private static final int SHAPE_CIRCLE = 0;
	private static final int SHAPE_ROUND = 1;
	private static final int SHAPE_UNSPEC = -1;
	
	private int mHeightType;
	private int mShapeType;
	
	public YxImageView(Context context, AttributeSet attrs)
	{
		this(context, attrs, 0);
	}

	public YxImageView(Context context)
	{
		this(context, null);
	}
	
	public YxImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.YxImageView, defStyle, 0);

		int n = a.getIndexCount();
		for (int i = 0; i < n; i++)
		{
			int attr = a.getIndex(i);
			switch (attr)
			{
			case R.styleable.YxImageView_fix_height:
				mHeightType = a.getInt(attr, TYPE_FIX_WIDTH);
				break;
			case R.styleable.YxImageView_type:
				mShapeType = a.getInt(attr, SHAPE_UNSPEC);
				break;
			default:
				break;
			}
		}
		a.recycle();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int measureWidth = getMeasuredWidth();
		int measureHeight = getMeasuredHeight();
		
		Drawable drawable = this.getDrawable();
		if (drawable != null && mShapeType != SHAPE_CIRCLE) {
			int drawableWidth = drawable.getIntrinsicWidth();
			int drawableHeight = drawable.getIntrinsicHeight();
			
			//Full fill height;
			// notice empty image file.
			// FIX_HEIGHT is the same with ImageView.
			 
			if (drawableWidth > 0 && drawableHeight > 0) {
				if (mHeightType == TYPE_FIX_HEIGHT) {
					int desiredWidth  = drawableWidth * getMeasuredWidth() / drawableHeight;
					setMeasuredDimension(desiredWidth, measureHeight);
				} else if (mHeightType == TYPE_FIX_WIDTH){
					int desiredHeight  = drawableHeight * getMeasuredWidth() / drawableWidth;
					setMeasuredDimension(measureWidth, desiredHeight);
				} else if (mHeightType == TYPE_FIX_HEIGHT_MATCH_WIDTH) {
					// default behavior
					setMeasuredDimension(measureWidth, measureHeight);
				}
			}
		}
	}
	
	@Override
	public void setImageBitmap(Bitmap bm) {
		super.setImageBitmap(bm);
		resizeImageViewIfNeeded();
	}
	
	private PaintFlagsDrawFilter pdf=new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
	
	@Override
	protected void onDraw(Canvas canvas) {
		
		Drawable drawable = getDrawable();
		Bitmap bitmap = null;
		if (drawable instanceof BitmapDrawable) {
			bitmap = ((BitmapDrawable) drawable).getBitmap();
		} else {
//		    super.onDraw(canvas);
			return;
		}
		
		// default image- solution 1
//	    canvas.drawBitmap(getCroppedBitmap(bitmap), 0, 0, null);
		
		if (mShapeType == SHAPE_ROUND) {
			Path path = new Path();
			int roundRdius = getResources().getDimensionPixelSize(R.dimen.round_radius);
			path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), roundRdius, roundRdius, Direction.CW);
			try {
				canvas.clipPath(path);
			} catch (UnsupportedOperationException e) {
				e.printStackTrace();
			}
		} else if (mShapeType == SHAPE_CIRCLE) {
			int doubleRadius = Math.min(getWidth(), getHeight());
			Path path = new Path();
			path.addCircle(doubleRadius / 2, doubleRadius / 2, doubleRadius / 2, Direction.CW);
			try {
				canvas.clipPath(path);
			} catch (UnsupportedOperationException e) {
				e.printStackTrace();
			}
		}
		super.onDraw(canvas);
	}
	
	public Bitmap getCroppedBitmap(Bitmap bmp) {
	    Bitmap sbmp = null;
	    int w = this.getWidth();
		int h = this.getHeight();
		
		if (mShapeType == SHAPE_ROUND) {
	        sbmp = Bitmap.createScaledBitmap(bmp, w, h, false);
		} else if (mShapeType == SHAPE_CIRCLE) {
			
			int doubleRadius = Math.min(w, h);
	        sbmp = Bitmap.createScaledBitmap(bmp, doubleRadius, doubleRadius, false);
		}
		
		if (sbmp == null) {
			return null;
		}
		
	    Bitmap output = Bitmap.createBitmap(sbmp.getWidth(),
	            sbmp.getHeight(), Config.ARGB_8888);
	    Canvas canvas = new Canvas(output);

	    final int color = 0xffa19774;
	    final Paint paint = new Paint();
	    final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

	    paint.setAntiAlias(true);
	    paint.setFilterBitmap(true);
	    paint.setDither(true);
	    canvas.drawARGB(0, 0, 0, 0);
	    paint.setColor(Color.parseColor("#BAB399"));

	    if (mShapeType == SHAPE_ROUND) {
			int roundRdius = getResources().getDimensionPixelSize(R.dimen.round_radius);
		    canvas.drawRoundRect(new RectF(rect), roundRdius, roundRdius, paint);
		} else if (mShapeType == SHAPE_CIRCLE) {
			int doubleRadius = Math.min(w, h);
		    canvas.drawCircle(doubleRadius / 2.0f, doubleRadius / 2.0f, doubleRadius / 2.0f, paint);
		}
	    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	    canvas.drawBitmap(sbmp, rect, rect, paint);


		return output;
	}
	
	private void resizeImageViewIfNeeded() {
		Drawable drawable = this.getDrawable();
		if (drawable != null) {
			int drawableWidth = drawable.getIntrinsicWidth();
			int drawableHeight = drawable.getIntrinsicHeight();
			
			//Full fill height;
			// notice empty image file.
			// FIX_HEIGHT is the same with ImageView.
			 
			if (drawableWidth > 0 && drawableHeight > 0) {
				if (mHeightType == TYPE_FIX_HEIGHT) {
					int desiredWidth  = drawableWidth * getMeasuredWidth() / drawableHeight;
					setMeasuredDimension(desiredWidth, getMeasuredHeight());
				} else if (mHeightType == TYPE_FIX_WIDTH) {
					int desiredHeight  = drawableHeight * getMeasuredWidth() / drawableWidth;
					setMeasuredDimension(getMeasuredWidth(), desiredHeight);
					
					this.getLayoutParams().height = desiredHeight;
					
					requestLayout();
					// update the embed list if needed
					ViewParent grandfather = this.getParent().getParent();
					if (grandfather instanceof YxListView) {
						Utility.setListViewHeightBasedOnChildren((ListView)grandfather);
					}
				} else if (mHeightType == TYPE_FIX_HEIGHT_MATCH_WIDTH) {
					// do nothing.
				}
			}
		}
	}
	
}
